﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using EasySL.Core;
using EasySL.Entity;
using EasySL.Controls;

namespace EasySL.UI.Controls
{
    public partial class ProductList
    {
        private void InitTask()
        {
            //getCategoryListTask
            this.getCategoryListTask = new Task();
            this.getCategoryListTask.BeforeStart += new EventHandler<EventArgs>(getCategoryListTask_BeforeStart);
            this.getCategoryListTask.Callback += new GetDataAsyncCompleted(this.GetCategoryListCallBack);

            //getProductListTask
            this.getProductListTask = new Task();
            this.getProductListTask.BeforeStart += new EventHandler<EventArgs>(getProductListTask_BeforeStart);
            this.getProductListTask.Callback += new GetDataAsyncCompleted(this.GetProductListCallBack);

            //A taskManager will send the getProductListTask after the callback of getCategoryListTask
            this.taskManager = new TaskManager();
            this.taskManager.TaskProcs.Add(this.getCategoryListTask);
            this.taskManager.TaskProcs.Add(this.getProductListTask);
        }

        //prepare the mothedName, returnType
        //which match the method of EasySL.Service/DataService.Method.cs
        void getCategoryListTask_BeforeStart(object sender, EventArgs e)
        {
            Task task = sender as Task;
            task.MethodName = "GetCategoryList";
            task.ReturnType = typeof(List<Category>);

            Window.ShowLoading("Get Categorys....");
        }

        //in the callback, we could update UI
        public void GetCategoryListCallBack(Response response)
        {
            this.categorys = response.Data as List<Category>;
        }

        void getProductListTask_BeforeStart(object sender, EventArgs e)
        {
            Task task = sender as Task;
            task.MethodName = "GetProductList";
            task.ReturnType = typeof(List<Product>);
            task.SetParameter("page", this.pageIndex);

            Window.ShowLoading("Get Products of page " + this.pageIndex.ToString());
        }

        public void GetProductListCallBack(Response response)
        {
            this.products = new ObservableCollection<Product>();

            foreach (Product product in (response.Data as List<Product>))
                this.products.Add(product);

            this.Dispatcher.BeginInvoke(() =>
            {
                this.productList.ItemsSource = this.products;
            });

            Window.HideLoading();
        }
        
        private Task getProductListTask;
        private Task getCategoryListTask;
        private TaskManager taskManager;
    }
}
